using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Universal.Application.Repositories;

namespace Universal.Api.Middleware;

/// <summary>
/// 权限认证中间件
/// </summary>
public class PermissionMiddleware
{
    private readonly RequestDelegate _next;

    public PermissionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, IPermissionService permissionService)
    {
        // 只对需要认证的接口进行权限检查
        if (context.User.Identity?.IsAuthenticated == true)
        {
            // 获取当前用户的ID - 尝试多种claim名称
            var userIdClaim = context.User.FindFirst("sub") ??
                             context.User.FindFirst(ClaimTypes.NameIdentifier) ??
                             context.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("{\"code\":401,\"message\":\"未授权访问\"}");
                return;
            }

            // 将用户ID存储到HttpContext中，供后续使用
            context.Items["UserId"] = userId;

            Console.WriteLine($"[PermissionMiddleware] 用户ID已设置: {userId}");
        }

        await _next(context);
    }
}

/// <summary>
/// 权限中间件扩展方法
/// </summary>
public static class PermissionMiddlewareExtensions
{
    public static IApplicationBuilder UsePermissionMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<PermissionMiddleware>();
    }
}
